﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace pictureAnalyse
{
    /// <summary>
    /// 定义当前类，用于存储图像的颜色值统计信息
    /// </summary>
    class PictureColors
    {
        public String picPath = "";         // 图像的路径信息
        public float[] C, A, R, G, B;       // 所有颜色、各颜色分量值统计信息

        public PictureColors(String picPath)
        {
            this.picPath = picPath;
            Bitmap pic = Bitmap.FromFile(picPath) as Bitmap;

            getColorCount(pic);         // 获取颜色值统计信息
            pic.Dispose();              // 释放当前图像资源
        }

        //获取图像对应的RGB图像颜色值统计信息
        public void getColorCount(Bitmap pic)
        {
            //Bitmap pic = ToBitmap(image);

            C = new float[256];

            A = new float[256];
            R = new float[256];
            G = new float[256];
            B = new float[256];

            Color c;
            for (int i = 0; i < pic.Height; i++)
            {
                for (int j = 0; j < pic.Width; j++)
                {
                    c = pic.GetPixel(j, i);             // 获取各像素的颜色值
                    //if (ignoreColors != null && ignoreColors.Contains(c)) return;

                    A[c.A]++;                           // 透明度信息
                    float weight = c.A / 255f;          // 根据透明度信息取颜色权值
                    float iC = (c.R + c.G + c.B) / 3;   // RGB混合色均值

                    R[c.R] += weight;       // 红色分量
                    G[c.G] += weight;       // 绿
                    B[c.B] += weight;       // 蓝
                    C[(int)iC] += weight;   // 均值
                }
            }
        }
       

        # region 其它函数

        /// <summary>
        /// 转化int为float
        /// </summary>
        public static float[] toFloat(int[] value)
        {
            float[] V = new float[value.Length];
            for (int i = 0; i < value.Length; i++)
            {
                V[i] = value[i];
            }
            return V;
        }

        //Image转化为Bitamap  
        public static Bitmap ToBitmap(Image pic)
        {
            //创建图像  
            Bitmap tmp = new Bitmap(pic.Width, pic.Height);                //按指定大小创建位图  
            Rectangle Rect = new Rectangle(0, 0, pic.Width, pic.Height);   //pic的整个区域  

            //绘制  
            Graphics g = Graphics.FromImage(tmp);                   //从位图创建Graphics对象  
            g.Clear(Color.FromArgb(0, 0, 0, 0));                    //清空  

            g.DrawImage(pic, Rect, Rect, GraphicsUnit.Pixel);       //从pic的给定区域进行绘制  

            return tmp;     //返回构建的新图像  
        }

        #endregion

    }
}
